const express = require('express');
const fs = require('fs');
const md5 = require('md5');
const session = require('express-session');

let router = express.Router();

router.use(session({
    secret: 'itcast',	  	  	//加密存储
    resave: false,			//客户端并行请求是否覆盖:true-是,false-否
    saveUninitialized: true   //初始化session存储
}));

router.use(function (req, res, next) {
    //当用户访问的不是注册页也不是登录才进去（判断用户是否有权访问）
   if (req.url !== '/login' && req.url !== '/reg') {
        if(!req.session.isLogin)  res.redirect('/login');
   }
   next();
});


router.get('/reg', function (req, res) {
   res.render('register.html');
});

router.post('/reg', function (req, res) {
    let postData = req.body;
    let fsData = fs.readFileSync('./db.json', 'utf8');
    let stus = JSON.parse(fsData).stus;
    let stu = stus.find(function (item) {
        return item.name === postData.name
    });

    if (stu) return res.status(200).json({status: 1, msg: '该用户已存在'});

    stus.push({
       name: postData.name,
       id: stus[stus.length - 1].id + 1,
       pwd: md5(postData.pwd),
        create_at: new Date()
    });
    let stuData = JSON.stringify({stus: stus})
    fs.writeFile('./db.json', stuData, function (err) {
        if (err) return res.status(500).json('服务器出错！！');
        res.status(200).json({status: 0, msg: '注册成功'});
    })

});


router.get('/login', function (req, res) {
   res.render('login.html')
});

router.post('/login', function (req, res) {
    let postData = req.body;
    let stusData = fs.readFileSync('./db.json', 'utf8');
    let stus = JSON.parse(stusData).stus;

    let isname = stus.find(function (item) {
        return item.name === postData.name;
    });
    if (!isname) return res.status(200).json({status: 1, msg: "登录失败，用户名不存在"});
    if (isname.pwd !== md5(postData.pwd)) return res.status(200).json({status: 1, msg: "登录失败，密码错误"});
    req.session.isLogin = true;
    req.session.userInfo = postData;
    return res.status(200).json({status: 0, msg: "注册成功"});
});


router.get('/out', function (req, res) {
   req.session.isLogin = null;
   req.session.userInfo = null;
   res.redirect('/login')
});

module.exports = router;